/*************************************************************************
    > File Name: TimeHandler.hh
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: 2015年08月01日 星期六 12时39分27秒
 ************************************************************************/
#ifndef	TIMEHANDLER_HH
#define TIMEHANDLER_HH

#include "__common.h"
#include <iostream>
using namespace std;

class TimeHandler {
	typedef boost::asio::deadline_timer DeadLineTimer;
	typedef boost::shared_ptr<boost::asio::deadline_timer> DeadLineTimerPtr;
	public:
		TimeHandler();
		TimeHandler(boost::asio::io_service& theIoService):
			myIoService(theIoService)
		{
		};
		TimeHandler(const TimeHandler& theTimeHandler):
			myIoService(theTimeHandler.myIoService)
		{
		};
		/*explicit TimeHandler(const int& theNum)
		{

		};*/

		void resetTimeOut(const long& theSecond,TimeOutCallbackFunc theTimeOutCallbackFunc)
		{
			if (myDeadLineTimer.get()) {
				// myDeadLineTimer->
			}
			myDeadLineTimer.reset(new DeadLineTimer(myIoService,boost::posix_time::seconds(theSecond)));
			myDeadLineTimer->async_wait(boost::bind(&TimeHandler::_timeout,this,
						boost::asio::placeholders::error,theSecond,myDeadLineTimer,theTimeOutCallbackFunc));

		};
	private:
		void _timeout(const boost::system::error_code& theErrorCode,const long& theSecond,
				DeadLineTimerPtr theDeadLineTimer, TimeOutCallbackFunc theTimeOutCallbackFunc)
		{
			if (!theErrorCode) {
				theTimeOutCallbackFunc();
				theDeadLineTimer->expires_at(theDeadLineTimer->expires_at()+boost::posix_time::seconds(theSecond));
				theDeadLineTimer->async_wait(boost::bind(&TimeHandler::_timeout,this,
							boost::asio::placeholders::error,theSecond,theDeadLineTimer,theTimeOutCallbackFunc));
			} else {
				cout << "[TimeHandler::_timeout] theErrorCode=" << theErrorCode.message();
			}
		};
	private:
		DeadLineTimerPtr			myDeadLineTimer;
		boost::asio::io_service&	myIoService;
};

#endif
